#! /usr/bin/env node
const fs = require('fs');
var program = require('./admin/node_modules/commander');
const chalk = require('./admin/node_modules/chalk')
// admin
const { createView } = require('./admin/auto-file/generateView')
const { createApi } = require('./admin/auto-file/generateApi');
const { createRouter } = require('./admin/auto-file/generateRouter');
const { createTabble } = require('./admin/auto-file/generateTabble');
const { createMock } = require('./admin/auto-file/generateMock');
// app
const { createAppApi } = require('./admin/auto-file/generateAppApi')

const log = message => console.log(chalk.green(`${message}`))

let dbPath = './app/cloudfunctions-aliyun/db_init.json'

let dbJson = fs.readFileSync(dbPath).toString()
dbJson = JSON.parse(dbJson)
let i = 0
let dbName = ''
let option = {}
for (let key in dbJson) {
  if (dbJson[key].auto) {
    i++
    if (i > 1) {
      console.log(chalk.red("出现多个要生成的数据表，最终只生成" + key + '表的数据'))
    }
    // 要生成的列的key
    option = dbJson[key].data[0]
    dbName = key
  }
}

program.parse(process.argv);
let options = {}
program.args.forEach(item => {
  options[item.split('=')[0]] = item.split('=')[1]
})
if (!options.url && !options.name && !options.path) {
  console.log(chalk.red("请执行 node crud name=侧边栏名字 path=目录名(路由名) Mock=true(要mock)非必要 noFn=true(不要生成云函数)非必要 noRouter=true(不要路由)非必要 "))
} else {
  log(`请输入要生成的文件名称、后台文件会生成在 option、api、mock、view的${options.path}目录下`)
  log(`云函数会生成在 /app/cloudfunctions-aliyun 的目录下`)
  log(`路由会生成在的/src/router/common/modules目录下`)
  process.stdin.on('data', async chunk => {
    const inputName = String(chunk).trim().toString()
    console.log()
    if (!options.noFn) {
      await createAppApi(options.path, inputName, dbName, option)
    }
    await createView(options.path, inputName)
    await createApi(options.path, inputName)
    if (!options.noRouter) {
      await createRouter(options, inputName)
    }
    await createTabble(options, [option], inputName)
    if (options.Mock) {
      await createMock(options, [option], inputName)
    }
    process.stdin.emit('end')
  })
  process.stdin.on('end', () => {
    log('生成结束')
    process.exit()
  })
}
